const { AdConfig, AdPosition, AdViewRecord, User } = require('../db');
const { checkEmptyParams } = require('./utils/requestUtils');
const { sendRes } = require('./utils/responseUtils');
const { dayjsNow, dayjsNowObj } = require('../utils/dayjsUtils');
const { Op, fn } = require('sequelize');
const { randomString } = require('../utils');
// 广告controller
module.exports = {
  adController(app) {
    // 添加配置
    app.post('/api/ad/addConfig', async (req, res) => {
      try {
        // const headers = req.headers;
        // const openId = headers['x-wx-openid'];
        // console.log('🚀 ~ openId', openId);
        // const query = req.query;
        const body = req.body;
        console.log('🚀 ~ body', body);
        checkEmptyParams(req, 'post', [
          'advertiser', 'type',
        ]);
        // advertiser广告主
        // type广告类型，cpc每次点击，cpm千次预览，cpa每次行动，cpr每次回应，cpp每次购买
        // days投放天数，默认30天
        const { advertiser, type, days = 30 } = body;
        const rlt = await AdConfig.create({
          adKey: randomString(8),
          advertiser, type,
          releaseEnd: dayjsNowObj().add(days, 'day'),
        });
        sendRes(res, { data: rlt });
      } catch (e) {
        console.error('❌ ~ 添加广告配置失败', e);
        sendRes(res, { code: -1, msg: e.message });
      }
    });
    // 获取广告配置
    app.get('/api/ad/getConfig', async (req, res) => {
      try {
        // const headers = req.headers;
        // const openId = headers['x-wx-openid'];
        // console.log('🚀 ~ openId', openId);
        const query = req.query;
        console.log('🚀 ~ query', query);
        const { pagePath = '' } = query;
        // const body = req.body;
        console.log('🚀 ~ dayjsNow()', dayjsNow());
        const configRlt = (await AdConfig.findAll({
          where: {
            isDelete: 0,
            releaseStart: {
              // [Op.lt]: dayjsNow(),
              [Op.lt]: fn('NOW'),
            },
            releaseEnd: {
              // [Op.gt]: dayjsNow(),
              [Op.gt]: fn('NOW'),
            },
          },
          order: [
            ['order', 'DESC']
          ],
          limit: 50,
        }))?.map(_ => _.dataValues);
        if (configRlt?.length) {
          for (let i = 0; i < configRlt.length; i++) {
            const item = configRlt[i];
            const positionWhere = {
              adKey: item.adKey,
              isDelete: 0,
            };
            if (pagePath) {
              positionWhere.pagePath = pagePath;
            }
            item.positions = (await AdPosition.findAll({
              where: positionWhere,
            }))?.map(_ => _.dataValues)?.map(_ => {
              _.positionId = _.id;
              delete _.id;
              return _;
            });
          }
        }
        // console.log('🚀 ~ configRlt', configRlt);
        sendRes(res, { data: configRlt });
      } catch (e) {
        console.error('❌ ~ 获取广告配置失败', e);
        sendRes(res, { code: -1, msg: e.message });
      }
    });
    // 用户的广告行动
    app.post('/api/ad/actionAd', async (req, res) => {
      try {
        const headers = req.headers;
        const openId = headers['x-wx-openid'];
        console.log('🚀 ~ openId', openId);
        // const query = req.query;
        const body = req.body;
        console.log('🚀 ~ body', body);
        if (!openId) {
          throw new Error('openId不能为空');
        }
        const userRlt = (await User.findAll({
          where: { openId },
        }))?.map(_ => _.dataValues);
        if (!userRlt?.length) {
          throw new Error('该用户不存在');
        }
        checkEmptyParams(req, 'post', [
          'adKey', 'actionType', 'positionId',
        ]);
        const { adKey, actionType, positionId } = body;
        // 校验adKey是否存在
        const adRlt = (await AdConfig.findAll({
          where: {
            adKey,
            isDelete: 0,
            releaseStart: {
              // [Op.lt]: dayjsNow(),
              [Op.lt]: fn('NOW'),
            },
            releaseEnd: {
              // [Op.gt]: dayjsNow(),
              [Op.gt]: fn('NOW'),
            },
          },
        }));
        if (!adRlt?.length) {
          throw new Error('找不到该广告');
        }
        // 校验positionId是否存在
        const adPositionRlt = (await AdPosition.findAll({
          where: { id: positionId, isDelete: 0 },
        }));
        if (!adPositionRlt?.length) {
          throw new Error('找不到该广告位');
        }
        // 插一条
        const rlt = await AdViewRecord.create({
          adKey, actionType, positionId, openId,
        });
        sendRes(res, { data: rlt.id });
      } catch (e) {
        console.error('❌ ~ 用户的广告行动', e);
        sendRes(res, { code: -1, msg: e.message });
      }
    });
  },
};
